package com.foodorder.service;

import com.foodorder.entity.StoreFollow;
import com.foodorder.repository.StoreFollowRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 店铺关注服务类
 */
@Service
@RequiredArgsConstructor
public class StoreFollowService {
    
    private final StoreFollowRepository storeFollowRepository;
    
    /**
     * 关注店铺
     */
    @Transactional
    public boolean followStore(Long userId, Long storeId) {
        // 检查是否已关注
        if (isFollowing(userId, storeId)) {
            return false;
        }
        
        StoreFollow storeFollow = new StoreFollow();
        storeFollow.setUserId(userId);
        storeFollow.setStoreId(storeId);
        storeFollowRepository.save(storeFollow);
        
        return true;
    }
    
    /**
     * 取消关注店铺
     */
    @Transactional
    public boolean unfollowStore(Long userId, Long storeId) {
        if (!isFollowing(userId, storeId)) {
            return false;
        }
        
        storeFollowRepository.deleteByUserIdAndStoreId(userId, storeId);
        return true;
    }
    
    /**
     * 检查是否关注了店铺
     */
    public boolean isFollowing(Long userId, Long storeId) {
        return storeFollowRepository.findByUserIdAndStoreId(userId, storeId).isPresent();
    }
    
    /**
     * 获取用户关注的店铺列表
     */
    public List<StoreFollow> getUserFollowedStores(Long userId) {
        return storeFollowRepository.findByUserIdOrderByFollowedAtDesc(userId);
    }
    
    /**
     * 获取店铺的关注者列表
     */
    public List<StoreFollow> getStoreFollowers(Long storeId) {
        return storeFollowRepository.findByStoreId(storeId);
    }
    
    /**
     * 获取店铺关注数
     */
    public long getStoreFollowCount(Long storeId) {
        return storeFollowRepository.countByStoreId(storeId);
    }
    
    /**
     * 获取用户关注的店铺数
     */
    public long getUserFollowCount(Long userId) {
        return storeFollowRepository.countByUserId(userId);
    }
    
    /**
     * 获取接收通知的关注者
     */
    public List<StoreFollow> getNotificationEnabledFollowers(Long storeId) {
        return storeFollowRepository.findNotificationEnabledFollowers(storeId);
    }
    
    /**
     * 更新通知设置
     */
    @Transactional
    public boolean updateNotificationSetting(Long userId, Long storeId, boolean receiveNotifications) {
        return storeFollowRepository.findByUserIdAndStoreId(userId, storeId)
                .map(follow -> {
                    follow.setReceiveNotifications(receiveNotifications);
                    storeFollowRepository.save(follow);
                    return true;
                })
                .orElse(false);
    }
} 